package com.rock.code.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 格式化工具类
 *
 * @author wuzeyuan
 * @date 20190307
 */
public class Formater {
    
    public final static String INVALID_DATE = "1970-01-01";
    
    public static String dateToString(Date dDate) {
        if (null == dDate) {
            return "";
        }
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
        if (formatter1.format(dDate).equals(INVALID_DATE)) {
            return "";
        }
        return formatter1.format(dDate);
    }
    
    public static String datetimeToString(Date date) {
        if (null == date) {
            return "";
        }
        if ("".equals(dateToString(date))) {
            return "";
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);
    }
    
    public static Date stringToDateTime(String cDate) throws ParseException {
        try {
            SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return formatter1.parse(cDate);
        } catch (ParseException e) {
            try {
                SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
                return formatter1.parse(cDate);
            } catch (ParseException ee) {
                try{
                    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    return formatter1.parse(cDate);
                }catch (ParseException ee1){
                    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
                    return formatter1.parse(cDate);
                }

            }
        }
    }
}
